<template>
  <div>
    <h2>聊天室</h2>

    <div class="ulul">
      <ul v-for="item in items" >
        <li class="li" v-if="item.username!=userinfo.username"><span class="time"> {{ item.time }}</span> <span
            class="name">{{ item.username }}</span> : &nbsp;&nbsp;&nbsp; <span>{{
            item.message
          }}</span>
        </li>

        <li class="left li" v-if="item.username==userinfo.username"><span>{{ item.message }} </span> &nbsp; &nbsp;&nbsp;
          :
          <span class="name">{{ item.username }}</span> &nbsp; &nbsp;&nbsp; <span class="time">{{ item.time }}</span>
        </li>
      </ul>
    </div>

    <div class="sendmes">
      <el-input class="input" v-model="message" placeholder="请输入消息"></el-input>
      <el-button class="button" @click="send">发送</el-button>
    </div>

  </div>
</template>

<script>

import store from "../../store";

const ws = new WebSocket("ws://127.0.0.1:8081/chat")


export default {
  name: "apps",

  data() {
    return {
      items: [],

      message: '',

      userinfo: '',
    }
  },

  methods: {


    send() {
      // if (!this.message.trim()) {
      //   return;
      // }
      const userinfo = store.getters.getUser;
      var date = new Date()


      ws.send(JSON.stringify({
        // time: "" + (date.getMonth() + 1) + "-" + date.getDay() +" "+ date.getHours()+":"+date.getMinutes()+":"+date.getSeconds(),
        time: date.toLocaleTimeString(),
        username: userinfo.username,
        message: this.message
      }))

      this.message = '';
    },


    handleOpen(e) {
      console.log(e)
    },

    handleMessage(e) {

      const msg = JSON.parse(e.data);
      this.items.push(msg)
      // console.log(e)
      window.scrollTo(0,document.body.scrollHeight);
    },


    handleError(e) {
      console.log(e)
    },

    handleClose(e) {
      console.log(e)
    },


  },


  mounted() {
    ws.addEventListener('open', this.handleOpen.bind(this), false)
    ws.addEventListener('error', this.handleError.bind(this), false)
    ws.addEventListener('message', this.handleMessage.bind(this), false)
    ws.addEventListener('close', this.handleClose.bind(this), false)
  },

  created() {
    var user = this.$store.getters.getUser;
    this.userinfo = user

  }


}
</script>

<style scoped>
h2 {
  color: #409EFF;
  text-align: center;
}

.ulul {
  margin-bottom: 130px;
}

.time {
  font-size: 13px;
  color: rgba(106, 115, 125, 0.75);
  font-weight: 500;
}

.name {
  font-weight: 600;
}

.left {
  text-align: right;
}

.input {
  width: 80%;
}

.button {
  width: 20%;
}

.sendmes {
  /*margin-bottom: 60px;*/
  position: fixed;
  bottom: 48px;
  width: 100%;
}

.li {
  margin: 5px;
}
</style>
